package com.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.gulimall.product.service.CategoryBrandRelationService;
import com.gulimall.product.vo.Catelog2Vo;
import org.apache.commons.lang.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.utils.PageUtils;
import com.common.utils.Query;

import com.gulimall.product.dao.CategoryDao;
import com.gulimall.product.entity.CategoryEntity;
import com.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    RedissonClient redissonClient;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {

        List<CategoryEntity> entities = baseMapper.selectList(null);

        List<CategoryEntity> collect = entities.stream().filter(categoryEntity ->
                categoryEntity.getParentCid() == 0
        ).map(menu -> {
            menu.setChildren(getChilrens(menu, entities));
            return menu;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());
        return collect;
    }


    @Override
    public void removeMenuByIds(List<Long> asList) {
        //TODO

        baseMapper.deleteBatchIds(asList);
    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        List<Long> parentPath = findParentPath(catelogId, paths);
        Collections.reverse(parentPath);
        return parentPath.toArray(new Long[parentPath.size()]);

    }

    /**
     * 级联更新所有关联的数据
     *
     * @param category
     * @CchaeEvict 失效模式
     * 同时进行删除多个缓存操作 @Caching
     * 指定删除某个分区下的所有数据   @CacheEvict(value = "category", allEntries = true)
     * 存储用一类型的数据: 都可以指定同一个分区
     */

//    @Caching(evict = {
//            @CacheEvict(value = "category", key = "'getLevelNoeCategory'"),
//            @CacheEvict(value = "category", key = "'getCatalogJson'")
//    })

    //    @CachePut   双写模式
    @CacheEvict(value = "category", allEntries = true)  //失效模式
    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());

    }


    /*
     *  spirng-cache 不足
     *      1,  读模式
     *          缓存穿透: 查询一个null数据. 解决: 缓存空数据; cache-null-values: true
     *          缓存击穿: 大量并发进来同时查询同一个过去的数据.解决: 加锁 默认是无加锁(加锁,解决击穿)
     *          缓存雪崩: 大量的key同时过期. 解决 加随便时间. 加上过期时间 spirng.cache.redis.time-to-live: 3600000
     *      2,  写模式: (缓存于数据库一致)
     *          读写加锁
     *          引入canal 感知到mysql的更新去更新数据库
     *          读多写多 直接去数据库查询
     *      总结:
     *          常规数据(读多写少, 及时性, 一致性要求不高的数据) 完全可以使用spring-cache 写模式(只要缓存的数据有过期时间就足够了)
     *          特殊数据: 特殊设计
     *
     *   原理:
     *      CacheManager(RedisCacheManager)->Cache(RedisCache)->Cache负责缓存的读写
     *
     *
     */

    @Cacheable(value = {"category"}, key = "#root.methodName", sync = true)
    //当前代表方法的结果需要缓存 ,如果缓存中有 ,方法不调用,如果缓存没有,会调用方法,最后将方法的数据放入缓存
    @Override
    public List<CategoryEntity> getLevelNoeCategory() {
        System.out.println("getLevelNoeCategory");
        long l = System.currentTimeMillis();
        List<CategoryEntity> entities = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
        return entities;
    }

    //TODO 产生堆外内存溢出 OutOfDirectMemoryError
    //spinrgboot2.0  默认使用lettuce-core作为操作redis客户端 他使用netty进行网络通信
    //lettuce的bug导致nettey堆外内存溢出  -Xmx300m netty如果没有指定堆外内存 默认使用 -Xmx300m
    // 可以通过-Dio.netty.maxDirectMemory进行设置


    @Cacheable(value = "category", key = "#root.method.name")
    @Override
    public Map<String, List<Catelog2Vo>> getCatalogJson() {
        System.out.println("查询了数据库");
        List<CategoryEntity> selectList = baseMapper.selectList(null);

        //查出所有分类
        List<CategoryEntity> levelNoeCategory = getParent_cid(selectList, 0L);

        Map<String, List<Catelog2Vo>> parentCid = levelNoeCategory.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {

            List<CategoryEntity> entities = getParent_cid(selectList, v.getCatId());
            List<Catelog2Vo> catelog2Vos = null;
            if (entities != null) {
                catelog2Vos = entities.stream().map(level2 -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, level2.getCatId().toString(), level2.getName());
                    //找当前二级分类的三级分类封装vo
                    List<CategoryEntity> level3Catelog = getParent_cid(selectList, level2.getCatId());

                    if (level3Catelog != null) {
                        List<Catelog2Vo.Catelog3Vo> collect = level3Catelog.stream().map(level3 -> {
                            Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(level2.getCatId().toString(), level3.getCatId().toString(), level3.getName());

                            return catelog3Vo;
                        }).collect(Collectors.toList());
                        catelog2Vo.setCatalog3List(collect);
                    }

                    return catelog2Vo;
                }).collect(Collectors.toList());
            }

            return catelog2Vos;
        }));

        return parentCid;
    }

    public Map<String, List<Catelog2Vo>> getCatalogJson2() {
        /**
         *      1.空结果缓存,解决缓存穿透
         *      2.设置过期时间(加随机值) 解决缓存雪崩
         *      3. 加锁 解决缓存击穿
         */
        String catalogJSON = redisTemplate.opsForValue().get("catalogJSON");
        if (StringUtils.isEmpty(catalogJSON)) {

            Map<String, List<Catelog2Vo>> catalogJsonFromDb = getCatalogJsonFromDb();
            return catalogJsonFromDb;
        }

        Map<String, List<Catelog2Vo>> restlu = JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catelog2Vo>>>() {
        });
        return restlu;
    }

    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDbWithRedisLockRedissonLock() {

        // 锁的名字 ,锁的粒度,越细越快
        // 锁的粒度 具体化
        RLock lock = redissonClient.getLock("CatalogJson-lock");
        lock.lock();

        Map<String, List<Catelog2Vo>> dataFromDb;
        try {
            dataFromDb = getDataFromDb();
        } finally {
            lock.unlock();
        }
        return getDataFromDb();
    }


    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDbWithRedisLock() {

        // 分布式锁 去redis占坑
        String uuid = UUID.randomUUID().toString();
        Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", "111", 300, TimeUnit.SECONDS);
        if (lock) {
            System.out.println("分布式锁成功");
            //加锁 执行业务
            //设置过期时间  必须和加锁同步, 原子性
            Map<String, List<Catelog2Vo>> dataFromDb;
            try {
                dataFromDb = getDataFromDb();
            } finally {
                String script = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
                Long lock1 = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList("lock", uuid));
            }

//            String lockValue = redisTemplate.opsForValue().get("lock");
//            if (uuid.equals(lockValue)) {
//                redisTemplate.delete("lock");
//            }

            return getDataFromDb();
        } else {
            System.out.println("获取分布式锁........失败");
            try {
                Thread.sleep(200);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return getCatalogJsonFromDbWithRedisLock();
        }

    }

    private Map<String, List<Catelog2Vo>> getDataFromDb() {
        String catalogJSON = redisTemplate.opsForValue().get("catalogJSON");
        if (!StringUtils.isEmpty(catalogJSON)) {
            Map<String, List<Catelog2Vo>> restlu = JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catelog2Vo>>>() {
            });
            return restlu;
        }
        System.out.println("查询了数据库");
        List<CategoryEntity> selectList = baseMapper.selectList(null);

        //查出所有分类
        List<CategoryEntity> levelNoeCategory = getParent_cid(selectList, 0L);

        Map<String, List<Catelog2Vo>> parentCid = levelNoeCategory.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {

            List<CategoryEntity> entities = getParent_cid(selectList, v.getCatId());
            List<Catelog2Vo> catelog2Vos = null;
            if (entities != null) {
                catelog2Vos = entities.stream().map(level2 -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, level2.getCatId().toString(), level2.getName());
                    //找当前二级分类的三级分类封装vo
                    List<CategoryEntity> level3Catelog = getParent_cid(selectList, level2.getCatId());

                    if (level3Catelog != null) {
                        List<Catelog2Vo.Catelog3Vo> collect = level3Catelog.stream().map(level3 -> {
                            Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(level2.getCatId().toString(), level3.getCatId().toString(), level3.getName());

                            return catelog3Vo;
                        }).collect(Collectors.toList());
                        catelog2Vo.setCatalog3List(collect);
                    }

                    return catelog2Vo;
                }).collect(Collectors.toList());
            }

            return catelog2Vos;
        }));


        String s = JSON.toJSONString(parentCid);
        redisTemplate.opsForValue().set("catalogJSON", s, 1, TimeUnit.DAYS);
        return parentCid;
    }

    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDb() {

        /*
        将数据库的多次查询变成一次
         */
        List<CategoryEntity> selectList = baseMapper.selectList(null);

        //查出所有分类
        List<CategoryEntity> levelNoeCategory = getParent_cid(selectList, 0L);

        Map<String, List<Catelog2Vo>> parentCid = levelNoeCategory.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {

            List<CategoryEntity> entities = getParent_cid(selectList, v.getCatId());
            List<Catelog2Vo> catelog2Vos = null;
            if (entities != null) {
                catelog2Vos = entities.stream().map(level2 -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, level2.getCatId().toString(), level2.getName());
                    //找当前二级分类的三级分类封装vo
                    List<CategoryEntity> level3Catelog = getParent_cid(selectList, level2.getCatId());

                    if (level3Catelog != null) {
                        List<Catelog2Vo.Catelog3Vo> collect = level3Catelog.stream().map(level3 -> {
                            Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(level2.getCatId().toString(), level3.getCatId().toString(), level3.getName());

                            return catelog3Vo;
                        }).collect(Collectors.toList());
                        catelog2Vo.setCatalog3List(collect);
                    }

                    return catelog2Vo;
                }).collect(Collectors.toList());
            }

            return catelog2Vos;
        }));

        return parentCid;
    }

    private List<CategoryEntity> getParent_cid(List<CategoryEntity> selectList, Long parent_cid) {
        List<CategoryEntity> collect = selectList.stream().filter(item -> item.getParentCid() == parent_cid).collect(Collectors.toList());
        return collect;
//        return baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", v.getCatId()));
    }


    private List<Long> findParentPath(Long catelogId, List<Long> paths) {
        paths.add(catelogId);
        CategoryEntity byId = this.getById(catelogId);
        if (byId.getParentCid() != 0) {
            findParentPath(byId.getParentCid(), paths);
        }
        return paths;
    }


    private List<CategoryEntity> getChilrens(CategoryEntity root, List<CategoryEntity> entities) {

        List<CategoryEntity> childdren = entities.stream().filter(categoryEntity -> {
            return categoryEntity.getParentCid() == root.getCatId();
        }).map(categoryEntity -> {
            categoryEntity.setChildren(getChilrens(categoryEntity, entities));
            return categoryEntity;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());

        return childdren;

    }
}
